﻿using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System.Text;
using Org.BouncyCastle.Math.EC;

namespace TempConsole;

public class GMCG
{
    public static void VerifyDemo()
    {
        var plaintext = "{\"return_msg\":\"集团无此账号\",\"msg_id\":\"cs20250108114032283365971835\",\"return_code\":10660041}";
        var sign = "MEUCIQDNYHU9juwd/6qLHif7qBHUSbZrMe64rcxhu3khN8GtvgIgES48ZPPZwS2fVS9s0eAzr26zuYPWMH7izuI3pQFkGFs=";
        var publicKey= "047b42f89f71cdc0e5d22c7ace5b677a9865b627b9da5a4e53cba54bbf3c819153bf443d65e0c1e6c1d4dbb8bbc8c80982f9042ef549d90c4af9c3ac0ca88a3dfe";

        // 将16进制公钥转换为字节数组
        byte[] publicKeyBytes = Hex.Decode(publicKey);

        // 创建ECPublicKeyParameters
        X9ECParameters ecParams = GMNamedCurves.GetByName("sm2p256v1");
        ECPoint q = ecParams.Curve.DecodePoint(publicKeyBytes);
        ECDomainParameters domainParams = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H);
        ECPublicKeyParameters publicKeyParam = new ECPublicKeyParameters(q, domainParams);

        // 初始化签名器
        ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
        signer.Init(false, publicKeyParam);

        // 转换数据为字节数组并验证签名
        byte[] dataBytes = Encoding.UTF8.GetBytes(plaintext);
        signer.BlockUpdate(dataBytes, 0, dataBytes.Length);
        byte[] signature = Convert.FromBase64String(sign);
        var b=signer.VerifySignature(signature);
        Console.WriteLine(b);
    }
}
